﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    [RequireComponent(typeof(Renderer))]
    [AddComponentMenu("Nirvana/UI/Language/Material I18N")]
    [DisallowMultipleComponent]
    [ExecuteInEditMode]
    public sealed class MatI18N : Translatable
    {
        [Serializable]
        private struct BindLanguageMaterial
        {
            [Tooltip("The languaget type.")]
            public I18NLanguageType languagetype;
            [Tooltip("The translate Material.")]
            public Material translate;
        };

        /// <summary>
        /// 内置翻译表，不通过keyid获取，直接设置
        /// </summary>
        [SerializeField]
        [Tooltip("The bind Language Material list.")]
        private List<BindLanguageMaterial> binds = new List<BindLanguageMaterial>();

        protected override void TranslateText()
        {
            var renderer = this.GetComponent<Renderer>();
            if (renderer == null)
            {
                return;
            }

            this.UpdateText(renderer);
        }

        private  void GetTranslate(out Material mat)
        {
            mat = null;
            I18NLanguageType language = I18N.Language;
            foreach (var f in binds)
            {
                if (f.languagetype == language)
                {
                    mat = f.translate;
                    return;
                }
            }

        }

        private void UpdateText(Renderer renderer)
        {
            if (Application.isPlaying)
            {
                Material msg;
                GetTranslate(out msg);
                renderer.sharedMaterial = msg;
            }
            else
            {

#if UNITY_EDITOR
                Material msg;
                GetTranslate(out msg);
                if (msg != null && msg.name != renderer.sharedMaterial.name)
                {
                    renderer.sharedMaterial = msg;
                    EditorUtility.SetDirty(renderer);
                }

#endif
            }

        }

    }
}

